import random
import re

from django.contrib.auth.backends import UserModel
from django.db.models import Q
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from tencentcloud.common.exception import TencentCloudSDKException

from SendMsgUtil import send_message
from jwttools import tooljwt
from tencentcloudapi import TencentCloudAPI


# Create your views here.
class LoginView(APIView):
    def post(self,request):
        # 1.获取参数
        print(request.data)
        # 2.验证验证码对不对
        try:
            api=TencentCloudAPI()
            # 向腾讯云发送请求，校验验证码
            result=api.captcha(request.data.get("ticket"),
                        request.data.get("randstr"),
                        request._request.META.get("REMOTE_ADDR"))
            print(result)
            #if result:
            if True:
                print("验证通过")
                # 3.验证码正确的情况下，验证用户名和密码
                username=request.data.get("username")
                password=request.data.get("password") #明文
                info=UserModel.objects.filter(Q(username=username)|Q(mobile=username)|Q(email=username)).first()
                if info is None:
                    return Response({"msg":"账号不存在","code":400})
                elif info.password==password:
                    # 生成一个token值给前端
                    token=tooljwt.getToken(info.id,info.username)
                    return Response({"msg":"登录成功","code":200,"data":token})
            else:
                print("验证失败")
                raise TencentCloudSDKException
        except TencentCloudSDKException as err:
           return Response({"msg":"验证码错误","code":400})


# 校验手机号是否可用
class MobileAPIView(APIView):
    def get(self,request,mobile):
        # 1.获取参数
        # 2.验证手机号是否可用
        if UserModel.objects.filter(mobile=mobile).exists():
            return Response({"message":"手机号已被注册","code":400})
        else:
            return Response({"message":"手机号可用","code":200})

# 发送手机验证码
class SendSmsAPIView(APIView):
    def get(self,request,mobile):
        # 1.获取手机号
        # 2.判断手机号是否已经发送过验证码 -基于redis
        redis = get_redis_connection("sms_code")
        rediscode=redis.get(mobile)  # 获取到该手机号对应的验证码
        if rediscode:
            #  2.1 发送过的，提示，验证码还在有效期
            return Response({"message":"验证码还在有效期","code":400})
        else:
            # 2.2 没有发送过，发送验证码
            code=str(random.randint(1000,9999)) #生成一个验证码
            redis.setex(mobile,60*5,code) # 存储到redis中，五分钟有效期
            send_message(mobile,code) #发送
            return Response({"message":"验证码发送成功","code":200})


# 注册
class RegisterView(APIView):
    def post(self,request):
        # 1.获取参数
        mobile=request.data.get("mobile")
        password=request.data.get("password")
        re_password=request.data.get("re_password")
        code=request.data.get("sms_code")
        # 2.校验数据的有效性
        # 2.1 验证手机号的有效性
        if not re.match(r"^1[3-9]\d{9}$",mobile):
            return Response({"message":"手机号格式不正确","code":400})
        # 2.2 验证密码和重复密码是否一致
        if password!=re_password:
            return Response({"message":"两次密码不一致","code":400})
        # 2.3 验证码是否正确
        redis = get_redis_connection("sms_code")
        rediscode=redis.get(mobile)
        print(rediscode)
        if rediscode is None:
            return Response({"message":"验证码已过期","code":400})
        elif rediscode.decode()!=code:
            return Response({"message":"验证码错误","code":400})
        else:
            # 3.保存用户信息
            UserModel.objects.create_user(username=f"用户{code}",mobile=mobile,password=password)
            # 4.返回结果
            token=tooljwt.getToken(mobile,password)
            return Response({"message":"注册成功","code":200,"data":token})



